#三数之和
from typing import  List
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = []
        n = len(nums)
        for i in range(n - 2):
            if nums[i] > 0:
                break  # 因为数组已排序，后面的数不可能使得三数之和为0
            if i > 0 and nums[i] == nums[i - 1]:
                continue  # 跳过重复的i
            left, right = i + 1, n - 1
            while left < right:
                s = nums[i] + nums[left] + nums[right]
                if s == 0:
                    res.append([nums[i], nums[left], nums[right]])
                    # 跳过左侧重复的元素
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    # 跳过右侧重复的元素
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1
                    left += 1
                    right -= 1
                elif s < 0:
                    left += 1
                else:
                    right -= 1
        return res